import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface UserState {
  loading: boolean
  error: string | null
  token: any
  is: boolean
}

const initialState: UserState = {
  loading: false,
  error: null,
  token: null,
  is: false,
}

export const signIn = createAsyncThunk(
  'user/signIn',
  async (
    paramaters: {
      email: string
      password: string
    },
    thunkAPI
  ) => {
    thunkAPI.dispatch(userSlice.actions.fetchStart())
    try {
      // const { data } = await axios.get(`${touristRouteId}`)
      const { data } = await axios.get(
        `https://mock.mengxuegu.com/mock/64fc8254e70b8004a69ea29a/https:/mock.TrvalData/auth/login`
      )
      thunkAPI.dispatch(userSlice.actions.fetchSuccess(data.token))
    } catch (error: any) {
      thunkAPI.dispatch(userSlice.actions.fetchFail(error.message))
    }
  }
)

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logOut: (state) => {
      state.token = null
      state.error = null
      state.loading = false
    },

    fetchStart: (state: any) => {
      // return { ...state, loading: true };
      state.loading = true
    },
    fetchSuccess: (state: any, action: any) => {
      state.token = action.payload
      state.loading = false
      state.error = null
      state.is = true
    },
    fetchFail: (state: any, action: PayloadAction<string | null>) => {
      //   const ddd = action.payload;
      state.loading = false
      state.error = action.payload
    },
  },
})
